package com.ng.finance.interceptor;

import com.alibaba.fastjson.JSON;
import com.ng.finance.api.service.WechatUserService;
import com.ng.finance.common.constant.ResultCode;
import com.ng.finance.common.pojo.Result;
import com.ng.finance.common.util.ApiTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author
 */
@Slf4j
@Component
public class ApiTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ApiTokenUtils apiTokenUtils;

    @Autowired
    private WechatUserService wechatUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {

        if (RequestMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }

      /*  final String unionId = apiTokenUtils.getUnionId();

        if (ObjectUtils.isEmpty(unionId)) {
            resultMessage("unionId Invalid ", response);
            return false;
        }
        EntityWrapper<WechatUser> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(WechatUser.UINIONID, unionId).eq(WechatUser.DEL_FLAG, 0);
        int count = wechatUserService.selectCount(entityWrapper);
        if (count == 0) {
            resultMessage("unionId is not binding ", response);
            return false;
        }*/
        return true;

    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {


    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {


    }

    private void resultMessage(String msg, HttpServletResponse response) {
        try {
            String resultJson = JSON.toJSONString(Result.build(ResultCode.UNAUTHORIZED, msg));
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(resultJson);
        } catch (IOException e) {

        }
    }


}
